<?php

namespace App\App\Services;

use SplFileObject;
use SplFileInfo;

class CsvReader
{
    protected $file;
    /**
     * @var SplFileObject
     */
    protected $resource;

    public function load($file)
    {
        $as = new SplFileInfo($file);

        if (!$as->isFile()) {
            throw new \InvalidArgumentException("{$file} is not a invalid file.");
        }

        if (!$as->isReadable()) {
            throw new \Exception("{$file} can not read.");
        }

        $this->resource = new SplFileObject($file, 'rb');

        return $this;
    }

    public function skip($line)
    {
        for ($i = 0; $i < $line; $i++) {
            $this->resource->fgets(); // passed
        }

        return $this;
    }

    public function read()
    {
        while ($this->resource->valid()) {
            yield $this->resource->fgetcsv();
        }
    }
}
